package com.example.testnborm

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import nborm.*
import kotlin.concurrent.thread

private const val TAG = "MainActivityT"

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DBHelper.init(this, "cc", 1, TestModel::class.java)
//        批量保存数据模型(数组、集合均支持)
        val array = arrayOf(Student("张三"), Student("李四"), Student("王五"), Student("赵四"))
        NBDao.saveAll(Student::class.java, array)
        NBDao.save(Student("hehehe").also { it.id = 3 }, ConflictPolicy.REPLACE)
        NBDao.query(Student::class.java)
    }

    fun startInsert(view: View) {
        val num = et_num.text.trim().toString()
        if (TextUtils.isDigitsOnly(num)) {
            val count = num.toInt()
            val sb = StringBuilder()
            sb.append("开始插入${count}条数据...")
            tv.text = sb.toString()
            val time = System.currentTimeMillis()
            thread {
                NBDao.saveAll(TestModel::class.java, count) {
                    TestModel(1, "", "", "", "", "", "", "")
                }
                runOnUiThread {
                    sb.append("结束插入${count}条数据。耗时：${System.currentTimeMillis() - time}毫秒")
                    tv.text = sb.toString()
                }
            }

        }
    }

    fun readRecord(view: View) {
        //读取所有记录
        val studentList = NBDao.query(Student::class.java).list()
        //读取所有studentName=张三的记录
        NBDao.query(
            Student::class.java,
            arrayOf("studentName"),
            "studentName=?",
            arrayOf("张三"),
            null,
            null,
            null,
            null
        ).list().forEach {
            Log.i(TAG, "readRecord: $it")
        }
        //读取单条记录
        val student = NBDao.query(
            Student::class.java,
            arrayOf("studentName"),
            "studentName=? and id =?",
            arrayOf("张三", "0"),
            null,
            null,
            null,
            null
        ).unique()

        TableHelper.getTableInfo(Student::class.java).dropTable()
    }


}
